package com.example.lin.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.lin.util.ExportUtil;
import com.example.lin.util.ImportUtil;
import com.example.lin.vo.DeDhlLableResp;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @className: DeDhlLable
 * @description: DE DHL 重新call lable 获取
 * @author: Lin.Gu
 * @date: 2025/8/19
 */
public class DeDhlLable {

    /**
     *  列头
     * "ID", "订单号", "服务", "请求报文"
     */
    @Test
    public void sendDeDhlLable() {

        RestTemplate restTemplate = RestTemplateProxy.getRestTemplate();

        String filePath = "C:\\Users\\181596\\Desktop\\嘉兴 DHL 重call.xlsx";
        int sheet = 0;
        List<List<Object>> list = ImportUtil.readExcelToList(filePath, sheet);
        List<Object[]> dataSuccess = new ArrayList<>();
        dataSuccess.add(new Object[]{"ID", "订单号", "服务", "请求报文", "执行脚本"});
        List<Object[]> dataError = new ArrayList<>();
        dataError.add(new Object[]{"ID", "订单号", "服务", "请求报文"});


        list.forEach(e -> {
            String id = e.get(0).toString();
            String trackingNumber = e.get(1).toString();
            String serviceCode = e.get(2).toString();
            String paramsJson = e.get(3).toString();

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");

            String url = "http://10.30.20.68:9150/mp-v2/shipmentLabel";

            // 解析JSON字符串为JSONObject
            JSONObject jsonParams = JSONObject.parseObject(paramsJson);
            jsonParams.put("businessOrderNo", trackingNumber.concat("-" + serviceCode));
            String modifiedJson = jsonParams.toJSONString();

            System.out.println("请求单号: " + trackingNumber);
            HttpEntity<String> entity = new HttpEntity(modifiedJson, headers);
            try {
                String result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
                //System.out.println("响应报文: " + JSON.toJSONString(result));
                DeDhlLableResp lableResp = JSON.parseObject(result, DeDhlLableResp.class);
                if (Objects.nonNull(lableResp) && Objects.nonNull(lableResp.getData())
                        && !StringUtils.isEmpty(lableResp.getData().getShipmentTrackingNo())) {
                    System.out.println("处理成功单号: " + trackingNumber);
                    DeDhlLableResp.DataLable data = lableResp.getData();

                    String sqlStr = "UPDATE t_waybill_dh_label SET last_mile_tracking_number='%s',label_url='%s',response_code=0,\n" +
                            "                            response_result='%s',modify_time=NOW(),modify_user_code='181596' where id='%s';";
                    String sql = String.format(sqlStr, data.getShipmentTrackingNo(), data.getShipmentLabel().getLabelUrl(),
                            result, id);
                    dataSuccess.add(new Object[]{id, trackingNumber, serviceCode, paramsJson, sql});
                } else {
                    throw new Exception("获取面单失败");
                }
            } catch (Exception exception) {
                System.out.println("处理异常单号: " + trackingNumber);
                dataError.add(new Object[]{id, trackingNumber, serviceCode, paramsJson});
            }
        });
        if (dataSuccess.size() > 1) {
            ExportUtil.exportTheFile("嘉兴DE-DHL面单", dataSuccess);
            System.out.println("处理成功单号条数:" + (dataSuccess.size()-1));
        }
        if (dataError.size() > 1) {
            ExportUtil.exportTheFile("嘉兴DE-DHL处理异常", dataError);
            System.out.println("处理异常单号条数:" + (dataError.size()-1));
        }
        System.out.println("处理完成");

    }

    public static void main(String[] args) {
        String result =  "{\"code\":0,\"data\":{\"shipmentTrackingNo\":\"00340434880562845956\",\"acceptLabelTime\":\"2025-08-19T12:34:37.000+00:00\",\"businessOrderNo\":\"ES1002969968469DH0102060200N-PLD1\",\"serviceCode\":\"PLD\",\"shipmentLabel\":{\"labelType\":\"URL\",\"labelUrl\":\"https://mphkfile.blob.core.windows.net/mp-prod/bizwork/label/DHL/2025/0819/00340434880562845956.pdf\"},\"shipmentNo\":\"1065392190764614317\",\"vendorCode\":\"DHL\"},\"errors\":[],\"fallback\":false,\"success\":true}";
        DeDhlLableResp lableResp = JSON.parseObject(result, DeDhlLableResp.class);
        System.out.println(lableResp);
    }

}
